<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="form.name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number.trim="form.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model.trim="form.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="handleClick">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="remove(item.id)">删除</button>
            <button @click="showEdit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
// vue2最容易犯的错误 折叠
// 后面的操作都是在发ajax
// 有些需求一开始不理解没思路 写css的时候慢慢就有思路 先简单后难
// 先静后动 有一天你上班的时候 把CSS写出来
// 看到表单 v-model
export default {
  data() {
    return {
      //   一般的数据都是来自后台ajax 绝对有id 假数据的 真实数据肯定有id
      arr: [
        { id: 1, name: "tom", sex: "男", age: 19 },
        { id: 2, name: "Jone", sex: "男", age: 21 },
        { id: 3, name: "lee", sex: "男", age: 18 },
      ],
      form: {
        id: "",
        name: "",
        age: "",
        sex: "",
      },
    };
  },
  methods: {
    handleClick() {
      if (this.form.name === "" || this.form.age === "" || this.form.sex === "")
        return alert("内容不能为空！");

      if (this.form.id !== "") {
        //xiugai
        const index = this.arr.findIndex((item) => item.id === this.form.id);
        this.arr[index] = { ...this.form };
        // this.arr.splice(index, 1, { ...this.form });
        this.form.id = "";
      } else {
        // tianjia
        const id = this.arr.length === 0 ? 1 : this.arr.slice(-1)[0].id + 1;
        this.form.id = id;
        this.arr.push({ ...this.form });
      }

      this.form.name = this.form.age = this.form.sex = "";
    },
    remove(a) {
      const index = this.arr.findIndex((item) => item.id === a);
      this.arr.splice(index, 1);
    },
    showEdit(b) {
      this.form = { ...this.arr.find((item) => item.id === b) };
      // console.log(this.form);
    },
  },
};
</script>
